import axios from 'axios'
// 引入store获取token
import { useTonkesStore } from '../../stores/tonkes'
import { ElMessage, ElLoading } from 'element-plus'

// 解构pinia中的state值
import { storeToRefs } from 'pinia'

let baseURL = ''
// console.log('node', process.env.NODE_ENV)
if (import.meta.env.MODE == 'development') {
  baseURL = 'http://big-event-vue-api-t.itheima.net' // 开发模式
} else if (import.meta.env.MODE == 'production') {
  baseURL = 'http://big-event-vue-api-t.itheima.net' // 生产模式
} else {
  baseURL = 'http://192.168.1.1:8080' // 测试服务器地址
}

const instance = axios.create({
  baseURL: baseURL,
  timeout: 5000,
})
//

let loadingInstance: any = null
// let loadingInstance: ReturnType<typeof ElLoading.service> | null = null;

instance.interceptors.request.use((config) => {
  console.log('config', config)
  // 1、设置token
  const userStore = useTonkesStore()
  const { userInfo } = storeToRefs(userStore)
  const token = userInfo.value?.token || ''
  if (token) {
    config.headers['Authorization'] = token
  }
  // 2、设置loading效果
  const options = {
    lock: true,
    text: '正在加载...',
    background: 'rgba(0, 0, 0, 0.7)',
  }
  loadingInstance = ElLoading.service(options)

  //  loadingInstance = ElLoading.service(options)
  // 3、对请求参数的处理
  return config
})

instance.interceptors.response.use(
  (response) => {
    console.log('response', response)
    if (loadingInstance) {
      loadingInstance.close()
    }
    if (response.status === 200) {
      if (response.data.code == 0) {
        ElMessage({
          message: response.data.message,
          type: 'success',
          duration: 1000,
        })
        return response.data
      } else {
        ElMessage({
          message: response.data.message,
          type: 'error',
        })
        return Promise.reject(response)
      }
    }
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          console.log('暂无权限')
          // 错误处理逻辑
          ElMessage.error(error.message || '暂无权限')
          break
        case 404:
          console.log('接口地址不存在')
          ElMessage.error(error.message || '接口地址不存在')
          break
        case 500:
          console.log('服务错误')
          ElMessage.error(error.message || '服务错误')
          break
        default:
          console.log('错误：', error.message)
      }
    } else if (error.request) {
      console.log('请求错误：', error.request)
    } else {
      console.log('其他错误：', error.message)
    }
    return Promise.reject(error)
  },
)

export default instance
